import { useState, useEffect } from 'react'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { View, Text, Image, ScrollView, Input } from '@tarojs/components'
import { Empty, Checkbox, Switch, Tabs, Button, Loading } from '@taroify/core'
import { ArrowLeft, FilterOutlined, StarOutlined } from '@taroify/icons'
import recipeService from '../utils/recipeService'
import './search.scss'

const SearchPage = () => {
  const [searchValue, setSearchValue] = useState('')
  const [searchResults, setSearchResults] = useState([])
  const [showFilter, setShowFilter] = useState(false)
  const [selectedTags, setSelectedTags] = useState([])
  const [isVegetarian, setIsVegetarian] = useState(false)
  const [searchMode, setSearchMode] = useState('name') // 'name', 'ingredient', 'tag'
  const [isLoading, setIsLoading] = useState(true)
  const [recipeData, setRecipeData] = useState([])
  const [error, setError] = useState(null)

  // 分类标签
  const categorizedTags = {
    菜系: ['川菜', '粤菜', '鲁菜', '东北菜'],
    口味: ['咸鲜', '酸甜', '辣', '清淡', '下饭'],
    类型: ['家常', '快手菜', '素食', '主食', '海鲜', '开胃']
  }

  // 加载食谱数据
  useEffect(() => {
    const fetchRecipeData = async () => {
      try {
        setIsLoading(true)
        // 从云端获取食谱数据
        const data = await recipeService.getRecipes()
        setRecipeData(data)

        // 获取页面参数，根据参数执行相应搜索
        handleParamsSearch(data)
      } catch (err) {
        console.error('获取食谱数据失败:', err)
        setError('加载失败，请重试')
        Taro.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      } finally {
        setIsLoading(false)
      }
    }

    fetchRecipeData()
  }, [])

  // 处理URL参数的搜索
  const handleParamsSearch = (data) => {
    const params = getCurrentInstance().router.params

    // 判断是否为过滤器模式
    if (params.filter === 'true') {
      setShowFilter(true)
    }

    // 如果有关键词参数，执行搜索
    if (params.keyword) {
      const keyword = decodeURIComponent(params.keyword)
      setSearchValue(keyword)
      searchRecipes(keyword, data)
    }

    // 如果有标签参数，执行按标签筛选
    if (params.tag) {
      const tag = decodeURIComponent(params.tag)
      setSelectedTags([tag])
      filterRecipes([tag], false, data)
    }

    // 如果有素食参数，执行素食筛选
    if (params.isVegetarian === 'true') {
      setIsVegetarian(true)
      filterRecipes([], true, data)
    }

    // 如果有食材ID列表参数
    if (params.ingredients) {
      try {
        const ingredientIds = JSON.parse(decodeURIComponent(params.ingredients))
        const results = data.filter((recipe) => ingredientIds.includes(recipe.id))
        setSearchResults(results)
      } catch (err) {
        console.error('解析食材ID参数失败:', err)
        setSearchResults([])
      }
    }
  }

  // 搜索处理
  const handleSearch = () => {
    console.log('执行搜索:', searchValue)
    if (searchValue && searchValue.trim()) {
      setIsLoading(true)
      setTimeout(() => {
        searchRecipes(searchValue.trim(), recipeData)
        setIsLoading(false)
      }, 500)
    }
  }

  // 搜索按钮点击处理
  const handleSearchButtonClick = () => {
    console.log('搜索按钮被点击')
    handleSearch()
  }

  // 当搜索框内容变化时
  const handleSearchChange = (e) => {
    console.log('搜索输入变化:', e.detail.value)
    setSearchValue(e.detail.value)
  }

  // 模糊搜索菜谱
  const searchRecipes = (keyword, data) => {
    let results = []

    if (!keyword || !keyword.trim()) {
      setSearchResults([])
      return
    }

    const lowerKeyword = keyword.toLowerCase()
    const dataToSearch = data || recipeData

    if (searchMode === 'name') {
      // 按菜名搜索
      results = dataToSearch.filter((recipe) => recipe.name.toLowerCase().includes(lowerKeyword))
    } else if (searchMode === 'ingredient') {
      // 按食材搜索
      results = dataToSearch.filter((recipe) =>
        recipe.ingredients.some((ingredient) => ingredient.toLowerCase().includes(lowerKeyword))
      )
    } else if (searchMode === 'tag') {
      // 按标签搜索
      results = dataToSearch.filter((recipe) => recipe.tags.some((tag) => tag.toLowerCase().includes(lowerKeyword)))
    }

    setSearchResults(results)
  }

  // 切换筛选面板
  const toggleFilter = () => {
    setShowFilter((prev) => !prev)
  }

  // 处理标签选择变化
  const handleTagsChange = (values) => {
    setSelectedTags(values)
  }

  // 处理素食选项变化
  const handleVegetarianChange = (checked) => {
    setIsVegetarian(checked)
  }

  // 应用筛选条件
  const applyFilter = () => {
    setIsLoading(true)
    setTimeout(() => {
      filterRecipes(selectedTags, isVegetarian, recipeData)
      setShowFilter(false)
      setIsLoading(false)
    }, 500)
  }

  // 根据筛选条件过滤菜谱
  const filterRecipes = (tags, vegetarian, data) => {
    let results = data || recipeData

    // 按标签筛选
    if (tags.length > 0) {
      results = results.filter((recipe) => tags.some((tag) => recipe.tags.includes(tag)))
    }

    // 按素食筛选
    if (vegetarian) {
      results = results.filter((recipe) => recipe.isVegetarian)
    }

    setSearchResults(results)
  }

  // 清空筛选条件
  const clearFilters = () => {
    setSelectedTags([])
    setIsVegetarian(false)
  }

  // 返回上一页
  const goBack = () => {
    // 获取页面栈
    const pages = Taro.getCurrentPages()
    // 如果只有一个页面（说明是从分享直接进入的首页）
    if (pages.length <= 1) {
      // 跳转到菜谱首页而不是使用navigateBack
      Taro.redirectTo({
        url: '/pages-recipe/index'
      })
    } else {
      Taro.navigateBack()
    }
  }

  // 查看菜谱详情
  const viewRecipeDetail = (id) => {
    Taro.navigateTo({
      url: `/pages-recipe/detail?id=${id}`
    })
  }

  // 切换搜索模式
  const handleSearchModeChange = (name) => {
    setSearchMode(name)
    if (searchValue.trim()) {
      searchRecipes(searchValue.trim(), recipeData)
    }
  }

  return (
    <View className='search-page'>
      {isLoading && (
        <View className='loading-container'>
          <Loading type='spinner' />
          <Text className='loading-text'>搜索中...</Text>
        </View>
      )}

      {error && (
        <View className='error-container'>
          <Text className='error-text'>{error}</Text>
          <Button
            color='primary'
            size='small'
            onClick={() => {
              setError(null)
              setIsLoading(true)
              recipeService
                .getRecipes()
                .then((data) => {
                  setRecipeData(data)
                  handleParamsSearch(data)
                })
                .catch((err) => {
                  console.error('重试失败:', err)
                  setError('重试加载失败，请稍后再试')
                })
                .finally(() => {
                  setIsLoading(false)
                })
            }}>
            重试
          </Button>
        </View>
      )}

      {!isLoading && !error && (
        <>
          <View className='header'>
            <View className='back-btn' onClick={goBack}>
              <ArrowLeft size='20' />
            </View>

            <View className='search-container'>
              <View className='search-input-box'>
                <Input
                  value={searchValue}
                  placeholder='搜索菜谱名称、食材或标签'
                  onInput={handleSearchChange}
                  className='search-input'
                  confirmType='search'
                  onConfirm={handleSearch}
                />
              </View>
              <View className='custom-search-btn' onClick={handleSearchButtonClick}>
                搜索
              </View>
            </View>

            {/* <View className='filter-toggle' onClick={toggleFilter}>
              <FilterOutlined size='20' color={showFilter ? '#ff6b6b' : '#666'} />
            </View> */}
          </View>

          {/* 搜索模式选择 */}
          {/* <View className='search-mode'>
            <Tabs value={searchMode} onChange={handleSearchModeChange}>
              <Tabs.TabPane name='name' title='按菜名' />
              <Tabs.TabPane name='ingredient' title='按食材' />
              <Tabs.TabPane name='tag' title='按标签' />
            </Tabs>
          </View> */}

          {/* 筛选面板 */}
          {showFilter && (
            <View className='filter-panel'>
              <View className='filter-header'>
                <Text className='filter-title'>筛选条件</Text>
                <Text className='clear-btn' onClick={clearFilters}>
                  清空
                </Text>
              </View>

              {/* 素食选项 */}
              {/* <View className='vegetarian-filter'>
                <Text>只看素食</Text>
                <Switch checked={isVegetarian} onChange={handleVegetarianChange} size='24' />
              </View> */}

              {/* 标签选择 */}
              {Object.entries(categorizedTags).map(([category, tags]) => (
                <View className='tag-category' key={category}>
                  <Text className='category-title'>{category}</Text>
                  <Checkbox.Group value={selectedTags} onChange={handleTagsChange}>
                    <View className='tags-grid'>
                      {tags.map((tag) => (
                        <Checkbox name={tag} key={tag} shape='square' className='tag-checkbox'>
                          {tag}
                        </Checkbox>
                      ))}
                    </View>
                  </Checkbox.Group>
                </View>
              ))}

              <Button color='primary' block className='apply-filter-btn' onClick={applyFilter}>
                应用筛选
              </Button>
            </View>
          )}

          {/* 搜索结果 */}
          <View className={`search-results ${showFilter ? 'results-with-filter' : ''}`}>
            {searchResults.length > 0 ? (
              <ScrollView scrollY className='results-container'>
                <View className='results-count'>
                  找到 <Text className='count'>{searchResults.length}</Text> 个菜谱
                </View>

                {searchResults.map((recipe) => (
                  <View key={recipe.id} className='recipe-item' onClick={() => viewRecipeDetail(recipe.id)}>
                    <Image className='recipe-image' src={recipe.image} mode='aspectFill' />
                    <View className='recipe-info'>
                      <Text className='recipe-name'>{recipe.name}</Text>

                      <View className='recipe-tags'>
                        {recipe.tags.slice(0, 2).map((tag, index) => (
                          <Text key={index} className='tag'>
                            {tag}
                          </Text>
                        ))}
                        {recipe.isVegetarian && <Text className='tag vegetarian'>素食</Text>}
                      </View>

                      <Text className='recipe-ingredients'>
                        {recipe.ingredients.slice(0, 3).join('、')}
                        {recipe.ingredients.length > 3 ? '...' : ''}
                      </Text>
                    </View>
                    <StarOutlined className='detail-icon' />
                  </View>
                ))}
              </ScrollView>
            ) : (
              <View className='empty-container'>
                <Empty>
                  <Empty.Image />
                  <Empty.Description>没有找到匹配的菜谱</Empty.Description>
                </Empty>
              </View>
            )}
          </View>
        </>
      )}
    </View>
  )
}

export default SearchPage
